from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import time
import re
import os


class AppVersionCrawler:
    def __init__(self):
        # 配置Chrome选项
        options = webdriver.ChromeOptions()
        options.add_argument('--headless')  # 无头模式
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')
        options.add_argument('--disable-gpu')
        options.add_argument('--window-size=1920,1080')
        options.add_argument(
            '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')

        # 手动指定ChromeDriver路径
        chromedriver_path = r"C:\Users\huf06\PycharmProjects\test\APPversion\chromedriver.exe"

        # 初始化浏览器驱动
        self.driver = webdriver.Chrome(executable_path=chromedriver_path, options=options)
        self.wait = WebDriverWait(self.driver, 15)

    def close(self):
        """关闭浏览器"""
        self.driver.quit()

    def extract_version_from_html(self, html_content):
        """从HTML内容中提取版本号"""
        # 使用正则表达式匹配版本号
        version_pattern = r'<div style="float-left">\s*版本号\s*</div>\s*<div style="float-right">\s*([\d.]+)\s*</div>'
        match = re.search(version_pattern, html_content, re.IGNORECASE)

        if match:
            return match.group(1)

        # 如果上面的模式不匹配，尝试更通用的模式
        version_pattern2 = r'版本号\s*</div>\s*<div[^>]*>\s*([\d.]+)\s*</div>'
        match = re.search(version_pattern2, html_content, re.IGNORECASE)

        if match:
            return match.group(1)

        return "未找到版本信息"

    def get_xiaomi_version(self, app_id):
        """获取小米应用商店版本信息"""
        try:
            url = f"https://app.mi.com/details?id={app_id}"
            print(f"正在访问小米应用商店: {url}")
            self.driver.get(url)

            # 等待页面加载
            time.sleep(5)

            # 获取页面HTML内容
            page_html = self.driver.page_source

            # 提取版本号
            version = self.extract_version_from_html(page_html)

            # 如果正则表达式方法失败，尝试使用XPath
            if version == "未找到版本信息":
                try:
                    # 查找包含"版本号"的元素
                    version_elements = self.driver.find_elements(By.XPATH, "//div[contains(text(), '版本号')]")
                    for element in version_elements:
                        # 获取父元素
                        parent = element.find_element(By.XPATH, "..")
                        # 查找同级元素中的版本号
                        sibling_elements = parent.find_elements(By.XPATH, "./div")
                        for sibling in sibling_elements:
                            sibling_text = sibling.text.strip()
                            # 检查是否是版本号格式
                            if re.match(r'^\d+\.\d+\.\d+$', sibling_text):
                                return sibling_text
                except:
                    pass

            return version
        except Exception as e:
            return f"获取小米版本失败: {str(e)}"

    def get_huawei_version(self, hw_id):
        """获取华为应用市场版本信息"""
        try:
            url = f"https://appgallery.huawei.com/app/{hw_id}"
            print(f"正在访问华为应用市场: {url}")
            self.driver.get(url)

            # 等待页面加载
            time.sleep(5)

            # 获取页面HTML内容
            page_html = self.driver.page_source

            # 提取版本号
            version = self.extract_version_from_html(page_html)

            # 如果正则表达式方法失败，尝试使用XPath
            if version == "未找到版本信息":
                try:
                    # 查找包含"版本号"的元素
                    version_elements = self.driver.find_elements(By.XPATH, "//*[contains(text(), '版本')]")
                    for element in version_elements:
                        # 获取父元素
                        parent = element.find_element(By.XPATH, "..")
                        # 查找同级元素中的版本号
                        sibling_elements = parent.find_elements(By.XPATH, "./*")
                        for sibling in sibling_elements:
                            sibling_text = sibling.text.strip()
                            # 检查是否是版本号格式
                            if re.match(r'^\d+\.\d+\.\d+$', sibling_text):
                                return sibling_text
                except:
                    pass

            return version
        except Exception as e:
            return f"获取华为版本失败: {str(e)}"

    def get_yyb_version(self, pkgname):
        """获取应用宝版本信息"""
        try:
            url = f"https://a.app.qq.com/o/simple.jsp?pkgname={pkgname}"
            print(f"正在访问应用宝: {url}")
            self.driver.get(url)

            # 等待页面加载
            time.sleep(5)

            # 获取页面HTML内容
            page_html = self.driver.page_source

            # 提取版本号
            version = self.extract_version_from_html(page_html)

            # 如果正则表达式方法失败，尝试使用XPath
            if version == "未找到版本信息":
                try:
                    # 查找包含"版本号"的元素
                    version_elements = self.driver.find_elements(By.XPATH, "//*[contains(text(), '版本号')]")
                    for element in version_elements:
                        # 获取父元素
                        parent = element.find_element(By.XPATH, "..")
                        # 查找同级元素中的版本号
                        sibling_elements = parent.find_elements(By.XPATH, "./*")
                        for sibling in sibling_elements:
                            sibling_text = sibling.text.strip()
                            # 检查是否是版本号格式
                            if re.match(r'^\d+\.\d+\.\d+$', sibling_text):
                                return sibling_text
                except:
                    pass

            return version
        except Exception as e:
            return f"获取应用宝版本失败: {str(e)}"

    def get_vivo_version(self, vivo_url):
        """获取vivo版本信息"""
        try:
            print(f"正在访问vivo应用商店: {vivo_url}")
            self.driver.get(vivo_url)
            # 等待页面加载
            time.sleep(5)

            # 获取页面HTML内容
            page_html = self.driver.page_source

            # 提取版本号
            version = self.extract_version_from_html(page_html)

            # 如果正则表达式方法失败，尝试使用XPath
            if version == "未找到版本信息":
                try:
                    # 查找包含"版本号"的元素
                    version_elements = self.driver.find_elements(By.XPATH, "//*[contains(text(), '版本信息')]")
                    for element in version_elements:
                        # 获取父元素
                        parent = element.find_element(By.XPATH, "..")
                        # 查找同级元素中的版本号
                        sibling_elements = parent.find_elements(By.XPATH, "./*")
                        for sibling in sibling_elements:
                            sibling_text = sibling.text.strip()
                            # 检查是否是版本号格式
                            if re.match(r'^\d+\.\d+\.\d+$', sibling_text):
                                return sibling_text
                except:
                    pass

            return version
        except Exception as e:
            return f"获取vivo版本失败: {str(e)}"



    def get_apple_version(self, apple_url):
        """获取苹果App Store版本信息"""
        try:
            print(f"正在访问苹果App Store: {apple_url}")
            self.driver.get(apple_url)

            # 等待页面加载
            time.sleep(5)
            # 苹果App Store的版本信息通常不在"版本号"标签旁边
            # 尝试查找版本信息
            try:
                version_element = self.driver.find_element(By.XPATH,
                                                           "//p[contains(@class, 'whats-new__latest__version')]")
                if version_element:
                    return version_element.text.replace('版本 ', '')
            except:
                pass

            # 备用查找方式
            elements = self.driver.find_elements(By.XPATH, "//*[contains(text(), '版本')]")
            for element in elements:
                text = element.text
                if "版本" in text:
                    version_match = re.search(r'版本\s*([\d.]+)', text)
                    if version_match:
                        return version_match.group(1)

            return "未找到版本信息"
        except Exception as e:
            return f"获取苹果版本失败: {str(e)}"

    def get_all_versions(self, app_id,apple_url,hw_id,vivo_url):
        """获取所有应用市场的版本信息"""
        results = {}

        # 获取各平台版本
        results["巨好播小米应用商店"] = self.get_xiaomi_version(app_id)
        results["巨好播华为应用市场"] = self.get_huawei_version(hw_id)
        results["巨好播应用宝"] = self.get_yyb_version(app_id)
        results["巨好播苹果App Store"] = self.get_apple_version(apple_url)
        results["巨好播VIVO应用商店"] = self.get_vivo_version(vivo_url)

        return results


def main():
    app_id = "com.chengguo.jhb"
    hw_id="C115385033"
    apple_url = "https://apps.apple.com/cn/app/%E5%B7%A8%E5%A5%BD%E6%92%AD/id6752237562"
    vivo_url="https://h5.appstore.vivo.com.cn/#/details?search_word=%E5%B7%A8%E5%A5%BD%E6%92%AD&search_action=4&app_id=4333508&app_pos=1&source=5&appId=4333508&frompage=searchResultApp&listpos=1"

    print("开始获取各应用市场版本信息...")
    print("=" * 50)

    # 创建爬虫实例
    crawler = AppVersionCrawler()

    try:
        # 获取所有版本信息
        results = crawler.get_all_versions(app_id, apple_url,hw_id,vivo_url)

        # 打印结果
        print("\n获取结果:")
        print("=" * 30)
        for platform, version in results.items():
            print(f"{platform}: {version}")
    except Exception as e:
        print(f"发生错误: {str(e)}")
        import traceback
        traceback.print_exc()
    finally:
        # 确保浏览器被关闭
        crawler.close()


if __name__ == "__main__":
    main()